package rsj.api.product;

import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.TableNode;
import common.util.Assert;
import common.util.BoxUtil;
import common.util.QueryRunnerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.user.BaseLink;
import rsj.service.IExecuteInterface;
import rsj.sql.ProductCategoryQueryDao;
import rsj.table.SYS_ORGPTYPE;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * 分类查询产品-整合库、自研类
 *
 * @author yuanqinglong
 * @since 2021/3/15 17:02
 */
@RestController
public class ProductCategoryQueryController extends BaseLink {

    @Autowired
    private ProductCategoryQueryDao productCategoryQueryDao;

    @Override
    @RequestMapping(value = "rsj_product_test_category")
    public Box executeLink(Box box) throws SQLException {
        MapNode data = box.getMapNode("data");
        String category = data.getValue("category");
        String orgId = data.getValue("org_id");
        Assert.isNotBlank(category, "测试分类不可为空");
        Assert.isNotBlank(orgId, "机构id不可为空");
        List<String> status = Arrays.asList(SYS_ORGPTYPE.Orgp_Status_Service, SYS_ORGPTYPE.Orgp_Status_Probation, SYS_ORGPTYPE.Orgp_Status_ServiceOver_LIMIT);
        TableNode product = productCategoryQueryDao.queryProductByTestCategory(orgId, category, status);
        MapNode mapNode = new MapNode().putTableNode("List", product);
        return BoxUtil.successBox(box).putMapNode("data", mapNode);
    }


    /**
     * 按测试分类查询产品
     *
     * @param category 产品分类  01=工商库，02=自研
     * @param orgId    机构id
     * @return 产品
     */
    private TableNode queryProductByTestCategory(String category, String orgId) {
        String sql = "SELECT prod_name,prod_id FROM sys.sys_status LEFT JOIN sys.sys_prod ON" +
                " prod_id = sta_prod_id WHERE sta_org_id = '" + orgId + "'" +
                "AND prod_test_type = '" + category + "' AND sta_status IN (" +
                "'" + SYS_ORGPTYPE.Orgp_Status_Service + "'," +
                "'" + SYS_ORGPTYPE.Orgp_Status_Probation + "'," +
                "'" + SYS_ORGPTYPE.Orgp_Status_ServiceOver_LIMIT + "')";
        return (TableNode) IExecuteInterface.doExecuteQuery(connection ->
                        QueryRunnerFactory.getQueryRunner().queryLinkTableNode(connection, sql),
                e -> logger.error("分类查询产品失败,{}", e));

    }


    public String queryProductByTestCategory(String orgId, String category, List<String> staStatus) {
        return "SELECT prod_name,prod_id FROM sys.sys_status LEFT JOIN sys.sys_prod ON prod_id = sta_prod_id WHERE sta_org_id = #{orgId}" +
                " AND prod_test_type = #{category} AND sta_status IN (#{staStatus})";
    }

}
